package com.basic.library.httpmanager;

import android.util.Base64;
import android.util.Log;

import com.basic.library.BuildConfig;
import com.basic.library.base.BaseApplication;
import com.basic.library.bean.HeaderInfo;
import com.basic.library.httpmanager.task.ApiHttpService;
import com.basic.library.utils.LocalData;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

import java.io.IOException;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import javax.net.ssl.SSLSocketFactory;

import io.reactivex.Observable;
import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;
import retrofit2.http.Body;
import retrofit2.http.FieldMap;
import retrofit2.http.FormUrlEncoded;
import retrofit2.http.GET;
import retrofit2.http.Multipart;
import retrofit2.http.POST;
import retrofit2.http.PartMap;
import retrofit2.http.QueryMap;
import retrofit2.http.Url;

public class RetrofitUtil {

    private static Retrofit mRetrofit;

    private static Retrofit initRetrofit() {
        if (mRetrofit == null) {
            OkHttpClient httpClient = null;
            OkHttpClient.Builder builder = new OkHttpClient.Builder();
            if (BuildConfig.DEBUG) {
                HttpLoggingInterceptor logging = new HttpLoggingInterceptor();
                logging.setLevel(HttpLoggingInterceptor.Level.BODY);
                builder.addInterceptor(logging);
            }
            addHeader(builder);
            Gson gson = new GsonBuilder()
                    .setDateFormat("yyyy-MM-dd'T'HH:mm:ssZ")
                    .create();//使用 gson coverter，统一日期请求格式

            SSLSocketFactory SSLSocketFactory = SslContextFactory
                    .getSSLSocketFactoryBilateral(BaseApplication.getInstance().getApplicationContext());
            httpClient = builder.
                    connectTimeout(10, TimeUnit.SECONDS)
                    .readTimeout(10, TimeUnit.SECONDS)
                    .writeTimeout(10, TimeUnit.SECONDS)
//                    .hostnameVerifier(new HostnameVerifier() {
//                        @Override
//                        public boolean verify(String hostname, SSLSession session) {
//                            return true;
//                        }
//                    })
                    .sslSocketFactory(SSLSocketFactory)
                    .build();

            mRetrofit = new Retrofit.Builder()
                    .baseUrl(ApiHttpService.BASE_URL)
                    .addConverterFactory(StringConverterFactory.create())
                    .addConverterFactory(GsonConverterFactory.create(gson))
                    .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                    .client(httpClient)
                    .build();
        }
        return mRetrofit;
    }

    public static void addHeader(OkHttpClient.Builder builder) {
        builder.addInterceptor(new Interceptor() {
            @Override
            public Response intercept(Chain chain) throws IOException {
                Request original = chain.request();
                // Request customization: add request headers
                HeaderInfo headerInfo = new HeaderInfo();
                headerInfo.setToken(LocalData.getInstance().getUserInfo().getToken());
                headerInfo.setUserId(LocalData.getInstance().getUserInfo().getId() + "");
                String headerStr = new Gson().toJson(headerInfo);
                String base64 = Base64.encodeToString(headerStr.getBytes(), Base64.NO_WRAP);
                if (BuildConfig.DEBUG) {
                    Log.d("EasyHttp-header", headerStr);
                    Log.d("EasyHttp-header-64", base64);
                }
                Request.Builder requestBuilder = original.newBuilder()
                        .addHeader("Custom", base64); // <-- this is the important line
                Request request = requestBuilder.build();
                return chain.proceed(request);
            }
        });
    }

    /**
     * 创建 RetrofitManage 服务
     *
     * @return ApiService
     */
    public static ApiService createApiService() {
        return initRetrofit().create(ApiService.class);
    }


    /**
     * Api请求
     */
    public interface ApiService {
        @GET
        Observable<String> getResponse(@Url String method
                , @QueryMap Map<String, String> options);

        @FormUrlEncoded
        @POST
        Observable<String> postResponse(@Url String method
                , @FieldMap Map<String, String> options);

        @POST
        Observable<String> bodyResponse(@Url String method
                , @Body Object options);

        @Multipart
        @POST
        Observable<String> uploadResponse(@Url String method
                , @PartMap Map<String, RequestBody> params);

    }
}
